<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <img :src="avatar" alt="" class="preview" v-if="avatar"/>
    <img v-else src="../../../assets/images/avatar.jpg" alt="" class="preview"/>

    <div class="btn-box">
      <input type="file" style="display:none" ref="inpFile" @change="getImage"/>
      <el-button type="primary" icon="el-icon-plus" @click="$refs.inpFile.click()">选择图片</el-button>
      <el-button type="success" icon="el-icon-upload" :disabled="!avatar" @click="uploadImage">上传头像</el-button
      >
    </div>
  </el-card>
</template>

<script>
export default {
  name: "UserAvatar",
  data() {
      return {
          avatar: '',
      };
  },
  methods:{
      getImage(e){
        //   console.log(e);
        const file = e.target.files[0]

        if (file){
            // 有东西
            // console.log('有点东西',file)
            const reader = new FileReader()
            // 将文件对象传入到reader.readAsDataURL(文件对象),可以读取文件对象数据
            reader.readAsDataURL(file)
            // 监听load事件,当文件对象中的数据读取完成,获取base64的地址
            reader.addEventListener('load',()=>{
                // reader.result 当前数据读取完成,获取base64的url
                // console.log(reader.result)
                // 将base64的图片地址,设置为img的src的地址
                this.avatar = reader.result
            })
        }

      },
     async uploadImage(){
        const {data:res} = await this.$axios.patch('/my/update/avatar',{avatar: this.avatar})
        // console.log(res);
        if (res.code !== 0) return this.$message.error(res.message)

        this.$message.success(res.message)

        this.$store.dispatch('initUserInfo')
      }
  }
};
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 350px;
  height: 350px;
}
</style>